//
//  singerSongTableview.m
//  A段项目音乐播放
//
//  Created by 太阳 on 15/5/23.
//  Copyright (c) 2015年 lanou3g.com蓝鸥科技. All rights reserved.
//
#import "DataBaseHandler.h"
#import "singerSongTableview.h"
#import "singerparticularscell.h"
#import <AFNetworking/AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "SingerModel.h"
#import "playViewController.h"
#import "myButton.h"
#import "SingerState.h"
#import "MJRefresh.h"
#import "PendulumView.h"
#import "CollectDatabase.h"
@interface singerSongTableview ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic ,retain)PendulumView *pendulum;

@end

@implementation singerSongTableview
- (void)dealloc
{
    [_mytableview release];
    [_modelarray release];
    [_singerPhoto release];
    [_mymodel release];
    [_blurImage release];
    [_context release];
    [_xuanran release];
    [_filter release];
    [_myview release];
    [_bigview release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.modelarray = [NSMutableArray array];
        
    }
    return self;
}

- (void)loadView
{
    [super loadView];
    [self.bigview setBackgroundColor:[UIColor yellowColor]];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self builtInterface];
    [self requestnet];
    [self requestpicture];
    UIColor *ballColor = [UIColor colorWithRed:0.47 green:0.60 blue:0.89 alpha:1];
    self.pendulum = [[PendulumView alloc] initWithFrame:self.bigview.bounds ballColor:ballColor];
    [self.mytableview addSubview:self.pendulum];
    
    
}
- (void)requestpicture
{
    NSString *str = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%ld?detail=true&app=ttpod&v=v7.9.1.2015050518&uid=&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=826886cd55c251bacd39b2d6523c12b126f3c590&idfa=27D84D88-B1C6-4173-B7C5-EE78CD26E7FB&utdid=VVrl99FV5JUDAA1STsAtAkrx&alf=201200&bundle_id=com.ttpod.music", self.num];
    NSString *address = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manger GET:address parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSData *data = [NSData dataWithData:responseObject];
        NSDictionary *bigdic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *datadic = [bigdic
                          objectForKey:@"data"];
        SingerModel *singermodel = [[[SingerModel alloc]init] autorelease];
        [singermodel setValuesForKeysWithDictionary:datadic];
        [self.singerPhoto sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", singermodel.picUrl]] placeholderImage:nil options:SDWebImageRetryFailed];
        
//        [self burlimageWithUrl:singermodel.picUrl];
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}
- (void)requestnet
{
    NSString *address = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%ld/songs?page=1&size=50&app=ttpod&v=v7.9.1.2015050518&uid=&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=826886cd55c251bacd39b2d6523c12b126f3c590&idfa=27D84D88-B1C6-4173-B7C5-EE78CD26E7FB&utdid=VVrl99FV5JUDAA1STsAtAkrx&alf=201200&bundle_id=com.ttpod.music", self.num];
    NSString *str = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manger GET:str parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSData *data = [NSData dataWithData:responseObject];
       
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", dic);
        NSArray *array = [dic objectForKey:@"data"];
        for (NSDictionary *dicc  in array) {
            SingerModel *model = [[[SingerModel alloc]init] autorelease];
            
            [model setValuesForKeysWithDictionary:dicc];
            NSArray *arrayyyy = [dicc objectForKey:@"auditionList"];
            NSInteger num = [arrayyyy count];
            if (num != 0) {
                NSDictionary *dicccc = [arrayyyy objectAtIndex:num - 1];
                [model setValuesForKeysWithDictionary:dicccc];
                [self.modelarray addObject:model];
            }
        }
        
        [self.mytableview reloadData];
        self.mytableview.separatorColor = [UIColor colorWithWhite:0.9 alpha:0.9];
        [self.pendulum removeFromSuperview];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {        NSLog(@"%@", error);
    }];

}

-(void)loctge
{
    self.i =2;
    
    NSString *address = [NSString stringWithFormat:@"http://api.dongting.com/song/singer/%ld/songs?page=%d&size=50&app=ttpod&v=v7.9.1.2015050518&uid=&mid=iPhone5S&f=f320&s=s310&imsi=&hid=&splus=8.3&active=1&net=2&openudid=826886cd55c251bacd39b2d6523c12b126f3c590&idfa=27D84D88-B1C6-4173-B7C5-EE78CD26E7FB&utdid=VVrl99FV5JUDAA1STsAtAkrx&alf=201200&bundle_id=com.ttpod.music", self.num,self.i];
    NSString *str = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    manger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manger GET:str parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSData *data = [NSData dataWithData:responseObject];
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@", dic);
        NSArray *array = [dic objectForKey:@"data"];
        for (NSDictionary *dicc  in array) {
            SingerModel *model = [[[SingerModel alloc]init] autorelease];
            [model setValuesForKeysWithDictionary:dicc];
            NSArray *arrayyyy = [dicc objectForKey:@"auditionList"];
            NSInteger num = [arrayyyy count];
            if (num != 0) {
                NSDictionary *dicccc = [arrayyyy objectAtIndex:num - 1];
                [model setValuesForKeysWithDictionary:dicccc];
                [self.modelarray addObject:model];
            }
        }
        [self.mytableview reloadData];
        //        [self.mytableview.footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error)
     {
         
         NSLog(@"%@", error);
         
     }];
    
    [self.mytableview.footer endRefreshing];
    
    self.i++;
    
}
- (void)builtInterface
{
    self.mytableview = [[[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64 * 2 + 30) style:UITableViewStylePlain] autorelease];
    self.mytableview.separatorColor = [UIColor clearColor];
    [self.mytableview.header beginRefreshing];
    [self.mytableview addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadgart)];
    [self.mytableview addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(loctge)];
    self.mytableview.delegate = self;
    self.mytableview.dataSource = self;
    [self.mytableview registerClass:[singerparticularscell class] forCellReuseIdentifier:@"cell"];

    [self.bigview addSubview:self.mytableview];
    
    self.singerPhoto = [[[UIImageView alloc]initWithFrame:CGRectMake(-50, 0, [UIScreen mainScreen].bounds.size.width , 600)] autorelease];
//    [self burlimage];
    
    
    [self.mytableview setBackgroundView:self.singerPhoto];
//    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
//    [view setBackgroundColor:[UIColor colorWithWhite:0.5 alpha:0.5]];
//    [self.mytableview addSubview:view];
//    self.mytableview.tableHeaderView = self.singerPhoto;
    
}
-(void)loadgart
{
    [self.modelarray removeAllObjects];
    [self.mytableview reloadData];
    [self requestnet];
    [self.mytableview.header endRefreshing];
    self.i =0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    playViewController *play = [playViewController shareStateOfViewcontroller];
    [play playWithModel:self.modelarray index:indexPath.row];
    
    [self.navigationController presentViewController:play animated:YES completion:nil];
}


#pragma mark - Table view data source





- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.modelarray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    singerparticularscell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        SingerModel *model = [self.modelarray objectAtIndex:indexPath.row];
    cell.songname.text = model.name;
    cell.singerName.text = model.singerName;
    [cell.button addTarget:self action:@selector(buttonaction:) forControlEvents:UIControlEventTouchUpInside];
//    [cell.button addButtonAction:self];
    
    cell.button.row = indexPath.row;
    
    cell.collectButton.row = indexPath.row;
    [cell.collectButton addTarget:self action:@selector(collectButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [cell setBackgroundColor:[UIColor colorWithWhite:0.2 alpha:0.1]];
    
    
    return cell;

}
// 收藏按钮
- (void)collectButtonAction:(myButton *)sender
{
    self.myview = [[[UIView alloc]init] autorelease];
    [self.myview setBackgroundColor:[UIColor colorWithWhite:0.2 alpha:0.8]];
    
    myButton *collectionButton = [myButton buttonWithType:UIButtonTypeSystem];
    collectionButton.layer.borderWidth = 1;
    collectionButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [collectionButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [collectionButton setTitle:@"收藏" forState:UIControlStateNormal];
    collectionButton.row = sender.row;
    //    [collectionButton setBackgroundColor:[UIColor colorWithRed:0.3 green:1 blue:1 alpha:1]];
    collectionButton.frame = CGRectMake(10, 30, [UIScreen mainScreen].bounds.size.width - 100 - 30, 30);
    [collectionButton addTarget:self action:@selector(collectionbuttonactions:) forControlEvents:UIControlEventTouchUpInside];
    [collectionButton setBackgroundColor:[UIColor colorWithRed:0.15 green:0.7 blue:0.6 alpha:1]];
    [self.myview addSubview:collectionButton];
    self.myview.layer.borderColor = [UIColor lightGrayColor].CGColor;
    self.myview.layer.borderWidth = 1;
    NSArray *array = [NSArray array];
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    array =  [dbHandler selecttableName];
    NSArray *array2 = [NSArray arrayWithArray:array];
    int i = 0;
    for (NSString *str in array2) {
        myButton *button = [myButton buttonWithType:UIButtonTypeSystem];
        //        [button setBackgroundColor:[UIColor redColor]];
        [button setTitle:str forState:UIControlStateNormal];
        button.layer.borderColor = [UIColor lightGrayColor].CGColor;
        button.layer.borderWidth = 1;
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.row = sender.row;
        [button setBackgroundColor:[UIColor colorWithRed:0.15 green:0.7 blue:0.6 alpha:1]];
        button.frame = CGRectMake(10, 75 + i * (30 + 20) , [UIScreen mainScreen].bounds.size.width - 100 - 30, 30);
        [button addTarget:self action:@selector(custonaction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = i + 1;
        [self.myview addSubview:button];
        i++;
    }
    [self.bigview addSubview:self.myview];
    [self.myview setBackgroundColor:[UIColor whiteColor]];
    self.myview.frame = CGRectMake(50, 150, [UIScreen mainScreen].bounds.size.width - 100, 120 + i * 40);
    
}
//自定歌单
- (void)custonaction:(myButton *)sender
{
    SingerModel *model = [self.modelarray objectAtIndex:sender.row];
    DataBaseHandler *da = [DataBaseHandler shareInstance];
    
    
    NSArray *array = [NSArray array];
    DataBaseHandler *dbHandler = [DataBaseHandler shareInstance];
    array =  [dbHandler selecttableName];
    NSArray *array2 = [NSArray arrayWithArray:array];
    
    NSString *srt = [array2 objectAtIndex:sender.tag - 1];
    
    [da insertmodel:model str:srt];
    UIAlertView *al = [[[UIAlertView alloc] initWithTitle:@"添加成功" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil] autorelease];
    [al show];
    [self.myview removeFromSuperview];
    
}

//收藏列表
- (void)collectionbuttonactions:(myButton *)inte
{
    SingerModel *model = [self.modelarray objectAtIndex:inte.row];
    [CollectDatabase insertWithModel:model];
    UIAlertView *alvi = [[[UIAlertView alloc]initWithTitle:@"收藏成功" message:nil delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil] autorelease];
    [alvi show];
    [self.myview removeFromSuperview];
    [self.bigview setBackgroundColor:[UIColor whiteColor]];
}



- (void)buttonaction:(myButton *)sender
{
    myButton *button = (myButton *)sender;
    SingerModel *model = [self.modelarray objectAtIndex:button.row];
    SingerState *singer = [SingerState shareOfPlayState];
    singer.addNum ++;  //添加数量
    
    [singer.playListAddress insertObject:model atIndex:singer.num + singer.addNum];
    playViewController *play = [[[playViewController alloc]init] autorelease];
    [play.songListTableview reloadData];
    NSLog(@"插入%@", model.name);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}
- (void)burlimageWithUrl:(NSString *)str
{
    NSURL *url = [NSURL URLWithString:str];
    CIImage *ciimage = [CIImage imageWithContentsOfURL:url];
    self.context = [CIContext contextWithOptions:nil];
    self.filter = [CIFilter filterWithName:@"CIGaussianBlur"];
    [self.filter setValue:ciimage forKey:kCIInputImageKey];
    [self.filter setValue:@2.0 forKey:@"inputRadius"];
    
    CIImage *outimage = [self.filter outputImage];
    
    CGImageRef cgimg = [self.context createCGImage:outimage fromRect:[outimage extent]];
    self.xuanran  = [UIImage imageWithCGImage:cgimg];
    CGImageRelease(cgimg);
    
    [self.singerPhoto setImage:self.xuanran];
    
}
@end
